package com.soft.sitegenerator.action;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.soft.sitegenerator.Component;
import com.soft.sitegenerator.DataBaseComponent;
import com.soft.sitegenerator.business.hibernate.NewsGroup;
import com.soft.sitegenerator.business.hibernate.Post;
import com.soft.sitegenerator.business.hibernate.User;
import com.soft.sitegenerator.exceptions.ObjectNotFoundException;
import com.soft.sitegenerator.form.DefaultForm;

public class DefaultAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		DefaultForm defaultForm = (DefaultForm) form;
		Component component = new DataBaseComponent();
		User user = (User) component.getBean("usersHib");
		
		user.setId((Long) request.getSession().getAttribute("USER_LOGIN"));
		
		// Si es el usuario admin
		if (user.getId()==null) {
			defaultForm.setNewMessages(-1);
			defaultForm.setTemplatesToComplete(-1);
			return mapping.findForward("showDefault");
		}
			
		
		try {
			user.load();
		} catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}
		
		defaultForm.setTemplatesToComplete(user.getTemplatesToComplete().size());
		
		int countPost = 0;
		for (Iterator itGroup = user.getNewsGroups().iterator(); itGroup.hasNext();) {
			NewsGroup newsGroup = (NewsGroup) itGroup.next();
			for (Iterator itPost = newsGroup.getPublishedPost().iterator(); itPost.hasNext();) {
				Post post = (Post) itPost.next();
				if (user.getLastPostRead()==null || post.getCreationDate().after(user.getLastPostRead()))
					countPost++;
			}
		}
		
		defaultForm.setNewMessages(countPost);
		
		return mapping.findForward("showDefault");
	}

}